package com.ipay.wechat.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import com.ipay.utils.StringUtil;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ipay.wechat.controller.LoginController;

public class HttpUtils {
    private static Logger logger = LoggerFactory
            .getLogger(LoginController.class);
    public static final String DEF_CHATSET = "UTF-8";
    public static final int DEF_CONN_TIMEOUT = 30000;
    public static final int DEF_READ_TIMEOUT = 30000;
    public static final String userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";
    public static final String APPKEY = "78b1655756dfad7fdac97762a19174e3";
    public static final String url = "http://v.juhe.cn/sms/send";// 请求接口地址

    //模板
    //【道合聚盈】您好，您已成功通过了商户申请！您的微信登录激活码为#code#。您的后台登录帐号为#username#，默认登录密码为#password#，其尽快登录商户后台修改密码。
    public static final String TEMPLATE_SHSHTG = "49348";
    //【道合聚盈】#merchant#已经添加你成为#shop#的收款员，登录名为#mobile#，邀请码是#code#。有效期为#hour#小时，请尽快验证
    public static final String TEMPLATE_TJSYY = "37717";
    //【道合聚盈】您的验证码是#code#。如非本人操作，请忽略本短信
    public static final String TEMPLATE_YZM = "37654";


    public static String requestHttp(String path, String method, String params) {
        HttpURLConnection connection = null;
        String result = "";
        try {
            URL url = new URL(path);
            connection = (HttpURLConnection) url.openConnection();
            if (method.equalsIgnoreCase("GET")) {
                connection.connect();
            } else if (method.equalsIgnoreCase("POST")) {
                connection.setDoInput(true);
                connection.setDoOutput(true);
                connection.setUseCaches(false);
                connection.connect();
                OutputStream os = connection.getOutputStream();
                os.write(params.getBytes("UTF-8"));
                os.close();
            }

            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), "UTF-8"));
            String lines;
            StringBuilder sb = new StringBuilder();
            while ((lines = reader.readLine()) != null) {
                sb.append(lines);
            }
            result = sb.toString();
            reader.close();
            connection.disconnect();
            return result;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;

    }

    /**
     * @param strUrl 请求地址
     * @param params 请求参数
     * @param method 请求方法
     * @return 网络请求字符串
     * @throws Exception
     */
    public static String net(String strUrl, Map params, String method)
            throws Exception {
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        String rs = null;
        try {
            StringBuffer sb = new StringBuffer();
            if (method == null || method.equals("GET")) {
                strUrl = strUrl + "?" + urlencode(params);
            }
            URL url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();
            if (method == null || method.equals("GET")) {
                conn.setRequestMethod("GET");
            } else {
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
            }
            conn.setRequestProperty("User-agent", userAgent);
            conn.setUseCaches(false);
            conn.setConnectTimeout(DEF_CONN_TIMEOUT);
            conn.setReadTimeout(DEF_READ_TIMEOUT);
            conn.setInstanceFollowRedirects(false);
            conn.connect();
            if (params != null && method.equals("POST")) {
                try {
                    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                    out.writeBytes(urlencode(params));
                    out.close();
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
            InputStream is = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sb.append(strRead);
            }
            rs = sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return rs;
    }

    // 将map型转为请求参数型
    public static String urlencode(Map<String, Object> data) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry i : data.entrySet()) {
            try {
                sb.append(i.getKey()).append("=")
                        .append(URLEncoder.encode(i.getValue() + "", "UTF-8"))
                        .append("&");
            } catch (UnsupportedEncodingException e) {
                logger.info(e.getMessage());
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    public static String getValidCode(String mobile, String tpl_id, String content) throws IOException {
        String result = null;
        Map params = new HashMap();// 请求参数
        params.put("mobile", mobile);// 接收短信的手机号码
        params.put("tpl_id", tpl_id);// 短信模板ID，请参考个人中心短信模板设置
        params.put("tpl_value", content);// 变量名和变量值对。如果你的变量名或者变量值中带有#&=中的任意一个特殊符号，请先分别进行urlencode编码后再传递，<a
        // href="http://www.juhe.cn/news/index/id/50"
        // target="_blank">详细说明></a>
        params.put("key", APPKEY);// 应用APPKEY(应用详细页查询)
        params.put("dtype", "json");// 返回数据的格式,xml或json，默认json
        try {
            result = net(url, params, "GET");
        } catch (Exception e) {
            logger.info(e.getMessage());
            e.printStackTrace();
        }
        return result;
    }


    /**
     * @param mobilePhone     接收短信的手机号码
     * @param tplId      短信模板ID，请参考个人中心短信模板设置
     * @param contentMap 短信模板参数
     * @return
     * @throws IOException
     */
    public static JSONObject getValidCode(String mobilePhone, String tplId, Map<String, String> contentMap) throws IOException {
        String tpl_id = "";
        String content = "";

        if (TEMPLATE_TJSYY.equals(tplId)) {
            String merchant = contentMap.get("merchant");
            String shop = contentMap.get("shop");
            String code = contentMap.get("code");
            String mobile = contentMap.get("mobile");
            content = URLEncoder.encode(
                    "#merchant#=" + merchant + " " + "&#shop#="
                            + shop + "&#mobile#=" + mobile
                            + "&#hour#=" + 1 + "&#code#=" + code
                            + "&#company#=道合聚盈", "utf-8");
            tpl_id=tplId;
        }else if(TEMPLATE_YZM.equals(tplId)){
            String mobileCode = contentMap.get("mobileCode");
            content = URLEncoder.encode("#code#=" + mobileCode + "&#company#=道合聚盈", "utf-8");
            tpl_id=tplId;
        }else if(TEMPLATE_SHSHTG.equals(tplId)){
            String inviteCode = contentMap.get("inviteCode");
            String userName = contentMap.get("userName");
            content = URLEncoder.encode(
                    "#code#=" + inviteCode + "&#username#="+ userName +
                            "&#password#=123456" + "&#company#=道合聚盈", "utf-8");
            tpl_id=tplId;
        }

        String result = "";
        if(StringUtil.isNotEmpty(tpl_id)&&StringUtil.isNotEmpty(content)) {
            Map params = new HashMap();// 请求参数
            params.put("mobile", mobilePhone);// 接收短信的手机号码
            params.put("tpl_id", tpl_id);// 短信模板ID，请参考个人中心短信模板设置
            params.put("tpl_value", content);// 变量名和变量值对。如果你的变量名或者变量值中带有#&=中的任意一个特殊符号，请先分别进行urlencode编码后再传递，<a
            // href="http://www.juhe.cn/news/index/id/50"
            // target="_blank">详细说明></a>
            params.put("key", APPKEY);// 应用APPKEY(应用详细页查询)
            params.put("dtype", "json");// 返回数据的格式,xml或json，默认json
            try {
                result = net(url, params, "GET");
            } catch (Exception e) {
                logger.info("短信发送异常",e);
            }
        }
        return JSONObject.fromObject(result);
    }

}
